﻿create proc DR_T1
@maNV char(10),
@ngayDi Datetime,
@maChuyen char(10),
@soHieu char(10)
as
begin tran
begin try		
		INSERT INTO DANGKY VALUES(@maNV,@ngayDi,@maChuyen,@soHieu)
		waitfor delay '00:00:10'	

		if(EXISTS(SELECT * From NhanVien Where MANV = @maNV AND LoaiNV = '1'))
		begin
			if((SELECT COUNT(*) From DangKy dk,NhanVien nv Where dk.MaNV = nv.MaNV AND nv.LoaiNV = '1' AND NgayDi = @ngayDi AND MaChuyen=@maChuyen AND  SoHieu=@soHieu) >  (SELECT SoTai From LichDi Where NgayDi = @ngayDi AND MaChuyen=@maChuyen AND  SoHieu=@soHieu))
			begin
				print N'Đã đủ số tài'
				rollback tran
				return
			end
		end

		if(EXISTS(SELECT * From NhanVien Where MANV = @maNV AND LoaiNV = '0'))
		begin
			if((SELECT COUNT(*) From DangKy dk,NhanVien nv Where dk.MaNV = nv.MaNV AND nv.LoaiNV = '0' AND NgayDi = @ngayDi AND MaChuyen=@maChuyen AND  SoHieu=@soHieu) >  (SELECT SoLo From LichDi Where NgayDi = @ngayDi AND MaChuyen=@maChuyen AND  SoHieu=@soHieu))
			begin
				print N'Đã đủ số lơ'
				rollback tran
				return
		   end
		end

	commit tran
	print N'Đăng ký thành công'
		
end try
begin catch
	declare @error varchar(1000)
	set @error = N'Đăng ký thất bại'
	raiserror (@error,16,1)
	rollback tran
	return
end catch
go		
